package cn.gs.global.server.msg;

// @author gs
import cn.gs.global.common.msg.IMessageServer;
import cn.gs.db.HibernateUtil;
import cn.gs.db.BoolTransaction;
import cn.gs.exchanger.ExchangerClient;
import cn.gs.exchanger.ExchangerException;
import cn.gs.exchanger.java.JavaExchangerClient;
import cn.gs.global.common.timer.TimerClientTool;
import cn.gs.global.common.msg.EType;
import cn.gs.global.table.msg.Message;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.UUID;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;

public class MessageServer implements IMessageServer {

    public static void main(String[] args) throws UnknownHostException, IOException, ExchangerException {
        Logger.getLogger("").setLevel(Level.ALL);
        for (Handler handler : Logger.getLogger("").getHandlers()) {
            handler.setLevel(Level.ALL);
        }
        JavaExchangerClient client = new JavaExchangerClient("127.0.0.1", ExchangerClient.PORT);
        INS.registerService(client);
    }
    public static final MessageServer INS = new MessageServer(new HibernateUtil());
    private final HibernateUtil util;
    TimerListenerImpl impl;

    public MessageServer(HibernateUtil util) {
        this.util = util;
    }

    public void registerService(JavaExchangerClient client) throws ExchangerException {
        client.register(this, IMessageServer.class);
        impl = new TimerListenerImpl();
        TimerClientTool.register(client, impl, "GsMsg" + UUID.randomUUID().toString().substring(30));
    }

    private int now() {
        return impl.date;
    }

    @Override
    public void msgCommon(EType type, int level, int fromG, int toG, int obj, long money, int count) {
        this.msgFull(type, level, fromG, toG, 0, obj, 0, 0, now(), money, count);
    }

    @Override
    public void msgFull(EType type, int level, int fromG, int toG, int midG, int obj, int begin, int end, int record, long money, int count) {
        Message m = new Message();
        m.setType(type);
        m.setLevel(level);
        m.setFromG(fromG);
        m.setToG(toG);
        m.setMidG(midG);
        m.setObj(obj);
        m.setBeginTime(begin);
        m.setEndTime(end);
        m.setRecordTime(record);
        m.setMoney(money);
        m.setCount(count);
        m.setAddTime(new Date());
        util.transactionSaveOrUpdate(m);
    }

    @Override
    public void msgOgnMoney(EType type, int fromG, long money) {
        this.msgCommon(type, type.getLevel(), 0, 0, 0, money, 0);
    }

    @Override
    public void msgOgnSimple(EType type, int fromG) {
        this.msgCommon(type, type.getLevel(), fromG, 0, 0, 0, 0);
    }

    @Override
    public void msgObjSimple(EType type, int obj) {
        this.msgCommon(type, type.getLevel(), 0, 0, obj, 0, 0);
    }
}
